package cz.cuni.amis.episodic.lisp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TraceUtils {

	/**
	 * Trims all but the first N elements of the traces.
	 * 
	 * @param traces
	 * @param trimmedTraceLength
	 * @return trimmed traces, values may be shared with the original traces
	 */
	public static <T> List<T[]> trimTrace(List<T[]> traces,
			int trimmedTraceLength) {
		List<T[]> trimmed = new ArrayList<>(traces.size());

		for (T[] trace : traces) {
			if (trace.length > trimmedTraceLength) {
				trimmed.add(Arrays.copyOf(trace, trimmedTraceLength));
			} else {
				// TODO just copy or reuse? we will reuse
				trimmed.add(trace);
			}
		}
		return trimmed;
	}
	
	/**
	 * Trims all but the first N elements and the last element of the trace.
	 * 
	 * @param traces
	 * @param trimmedTraceLength
	 * @return trimmed traces, values may be shared with the original traces
	 */
	public static <T> List<T[]> trimTraceLeaveLast(List<T[]> traces,
			int trimmedTraceLength) {
		int firtsN = trimmedTraceLength -1;
		List<T[]> trimmed = new ArrayList<>(traces.size());

		for (T[] trace : traces) {
			if (trace.length >= trimmedTraceLength) {
				T[] copy = Arrays.copyOf(trace, trimmedTraceLength);
				// add the last
				copy[copy.length-1] = trace[trace.length-1];
				trimmed.add(copy);
			} else {
				// TODO just copy or reuse? we will reuse
				trimmed.add(trace);
			}
		}
		return trimmed;
	}


	/**
	 * 
	 * @param traces
	 * @param levelToPadd
	 * @return
	 */
	public static <T> List<T[]> padDown(List<T[]> traces, int levelToPadd) {
		List<T[]> padded = new ArrayList<>(traces.size());
		
		for(T[] trace : traces) {
			if(trace.length < levelToPadd) {
				T[] newTrace = Arrays.copyOf(trace, levelToPadd);
				Arrays.fill(newTrace, trace.length, newTrace.length, trace[trace.length-1]);
				padded.add(newTrace);
			} else {
				// TODO just copy or reuse? we will reuse
				padded.add(trace);
			}
		}
		return padded;
	}

}
